package com.atlin.project.fileService.service;

import com.atlin.project.common.ErrorCode;
import com.atlin.project.config.AtLinConfig;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.fileService.BaseFileService;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.enums.FileUploadBizEnum;
import com.atlin.project.utils.file.LocalFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @author atlin
 * @description 本地文件存储服务
 * @createDate 2025/1/1 9:47
 */
@Component
@Slf4j
public class NativeFileService extends BaseFileService {
    @Resource
    private AtLinConfig atLinConfig;


    @Override
    public AtLinConfig getConfig() {
        return atLinConfig;
    }

    @Override
    public String doSave(MultipartFile multipartFile, SysUser loginUser, FileUploadBizEnum fileUploadBizEnum) {
        configCheck();
        fileCheck(fileUploadBizEnum, multipartFile);

        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String fileName = uuid + "-" + multipartFile.getOriginalFilename();
        String filePath = buildPath(loginUser.getId(), fileUploadBizEnum.getValue());

        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            // 返回可访问地址
            return LocalFileUtil.fileSave(file, filePath, fileName);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("temp file delete error, filepath = {}", filePath + '/' + fileName);
                }
            }
        }
    }

    @Override
    public void doRead(String path, HttpServletRequest request, HttpServletResponse response) {
        LocalFileUtil.previewFile(path, response);
    }

    @Override
    public String buildPath(long userId, String bizType) {
        return String.format("%s/%s/%s/%s", atLinConfig.getFilePath(), bizType, userId, System.currentTimeMillis());
    }

    @Override
    protected void configCheck() {
        super.configCheck();
        String filePath = atLinConfig.getFilePath();
        if (StringUtils.isBlank(filePath)) {
            log.error("[本地文件服务] 文件存储路径不存在");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件服务异常");
        }
    }

}
